import numpy as np
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import pandas as pd
from tensorflow import keras
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import MinMaxScaler
from matplotlib import pyplot
import plotly.graph_objects as go
import math
import seaborn as sns
from sklearn.metrics import mean_squared_error
np.random.seed(1)
tf.random.set_seed(1)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, GRU, Dropout, RepeatVector, TimeDistributed
from keras import backend
MODELFILENAME = 'MODELS/GRU_3h_TFM'
TIME_STEPS=18 #3h
CMODEL = GRU
MODEL = "GRU"
UNITS=55
DROPOUT=0.118
ACTIVATION='tanh'
OPTIMIZER='adamax'
EPOCHS=36
BATCHSIZE=9
VALIDATIONSPLIT=0.2
# Code to read csv file into Colaboratory:
# from google.colab import files
# uploaded = files.upload()
# import io
# df = pd.read_csv(io.BytesIO(uploaded['SentDATA.csv']))
# Dataset is now stored in a Pandas Dataframe
df = pd.read_csv('../../data/dadesTFM.csv')
df.reset_index(inplace=True)
df['Time'] = pd.to_datetime(df['Time'])
df = df.set_index('Time')
columns = ['PM1','PM25','PM10','PM1ATM','PM25ATM','PM10ATM']
df1 = df.copy();
df1 = df1.rename(columns={"PM 1":"PM1","PM 2.5":"PM25","PM 10":"PM10","PM 1 ATM":"PM1ATM","PM 2.5 ATM":"PM25ATM","PM 10 ATM":"PM10ATM"})
df1['PM1'] = df['PM 1'].astype(np.float32)
df1['PM25'] = df['PM 2.5'].astype(np.float32)
df1['PM10'] = df['PM 10'].astype(np.float32)
df1['PM1ATM'] = df['PM 1 ATM'].astype(np.float32)
df1['PM25ATM'] = df['PM 2.5 ATM'].astype(np.float32)
df1['PM10ATM'] = df['PM 10 ATM'].astype(np.float32)
df2 = df1.copy()
train_size = int(len(df2) * 0.8)
test_size = len(df2) - train_size
train, test = df2.iloc[0:train_size], df2.iloc[train_size:len(df2)]
train.shape, test.shape
((3991, 7), (998, 7))
#Standardize the data
for col in columns:
scaler = StandardScaler()
train[col] = scaler.fit_transform(train[[col]])
<ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]])
def create_sequences(X, y, time_steps=TIME_STEPS):
Xs, ys = [], []
for i in range(len(X)-time_steps):
Xs.append(X.iloc[i:(i+time_steps)].values)
ys.append(y.iloc[i+time_steps])
return np.array(Xs), np.array(ys)
X_train, y_train = create_sequences(train[[columns[1]]], train[columns[1]])
#X_test, y_test = create_sequences(test[[columns[1]]], test[columns[1]])
print(f'X_train shape: {X_train.shape}')
print(f'y_train shape: {y_train.shape}')
X_train shape: (3973, 18, 1) y_train shape: (3973,)
#afegir nova mètrica
def rmse(y_true, y_pred):
return backend.sqrt(backend.mean(backend.square(y_pred - y_true), axis=-1))
model = Sequential()
model.add(CMODEL(units = UNITS, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(rate=DROPOUT))
model.add(TimeDistributed(Dense(1,kernel_initializer='normal',activation=ACTIVATION)))
model.compile(optimizer=OPTIMIZER, loss='mae',metrics=['mse',rmse])
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= gru (GRU) (None, 18, 55) 9570 _________________________________________________________________ dropout (Dropout) (None, 18, 55) 0 _________________________________________________________________ time_distributed (TimeDistri (None, 18, 1) 56 ================================================================= Total params: 9,626 Trainable params: 9,626 Non-trainable params: 0 _________________________________________________________________
history = model.fit(X_train, y_train, epochs=EPOCHS, batch_size=BATCHSIZE, validation_split=VALIDATIONSPLIT,
callbacks=[keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, mode='min')], shuffle=False)
Epoch 1/36 354/354 [==============================] - 9s 25ms/step - loss: 0.4235 - mse: 0.6615 - rmse: 0.4574 - val_loss: 0.2779 - val_mse: 0.2813 - val_rmse: 0.3092 Epoch 2/36 354/354 [==============================] - 4s 11ms/step - loss: 0.3560 - mse: 0.5801 - rmse: 0.3915 - val_loss: 0.2629 - val_mse: 0.2708 - val_rmse: 0.2893 Epoch 3/36 354/354 [==============================] - 4s 11ms/step - loss: 0.3461 - mse: 0.5687 - rmse: 0.3794 - val_loss: 0.2573 - val_mse: 0.2672 - val_rmse: 0.2812 Epoch 4/36 354/354 [==============================] - 5s 15ms/step - loss: 0.3408 - mse: 0.5633 - rmse: 0.3726 - val_loss: 0.2537 - val_mse: 0.2651 - val_rmse: 0.2759 Epoch 5/36 354/354 [==============================] - 5s 13ms/step - loss: 0.3378 - mse: 0.5603 - rmse: 0.3685 - val_loss: 0.2511 - val_mse: 0.2640 - val_rmse: 0.2727 Epoch 6/36 354/354 [==============================] - 6s 18ms/step - loss: 0.3359 - mse: 0.5585 - rmse: 0.3660 - val_loss: 0.2499 - val_mse: 0.2635 - val_rmse: 0.2711 Epoch 7/36 354/354 [==============================] - 6s 18ms/step - loss: 0.3342 - mse: 0.5573 - rmse: 0.3642 - val_loss: 0.2494 - val_mse: 0.2635 - val_rmse: 0.2706 Epoch 8/36 354/354 [==============================] - 6s 17ms/step - loss: 0.3335 - mse: 0.5563 - rmse: 0.3635 - val_loss: 0.2494 - val_mse: 0.2635 - val_rmse: 0.2704 Epoch 9/36 354/354 [==============================] - 5s 14ms/step - loss: 0.3329 - mse: 0.5560 - rmse: 0.3630 - val_loss: 0.2488 - val_mse: 0.2636 - val_rmse: 0.2698 Epoch 10/36 354/354 [==============================] - 6s 16ms/step - loss: 0.3322 - mse: 0.5552 - rmse: 0.3625 - val_loss: 0.2486 - val_mse: 0.2638 - val_rmse: 0.2695 Epoch 11/36 354/354 [==============================] - 5s 15ms/step - loss: 0.3315 - mse: 0.5547 - rmse: 0.3622 - val_loss: 0.2493 - val_mse: 0.2639 - val_rmse: 0.2702 Epoch 12/36 354/354 [==============================] - 5s 15ms/step - loss: 0.3314 - mse: 0.5546 - rmse: 0.3623 - val_loss: 0.2490 - val_mse: 0.2642 - val_rmse: 0.2697 Epoch 13/36 354/354 [==============================] - 6s 16ms/step - loss: 0.3311 - mse: 0.5538 - rmse: 0.3620 - val_loss: 0.2492 - val_mse: 0.2643 - val_rmse: 0.2702 Epoch 14/36 354/354 [==============================] - 5s 15ms/step - loss: 0.3309 - mse: 0.5536 - rmse: 0.3619 - val_loss: 0.2495 - val_mse: 0.2643 - val_rmse: 0.2704 Epoch 15/36 354/354 [==============================] - 5s 15ms/step - loss: 0.3305 - mse: 0.5535 - rmse: 0.3617 - val_loss: 0.2495 - val_mse: 0.2645 - val_rmse: 0.2703
import matplotlib.pyplot as plt
plt.plot(history.history['loss'], label='MAE Training loss')
plt.plot(history.history['val_loss'], label='MAE Validation loss')
plt.plot(history.history['mse'], label='MSE Training loss')
plt.plot(history.history['val_mse'], label='MSE Validation loss')
plt.plot(history.history['rmse'], label='RMSE Training loss')
plt.plot(history.history['val_rmse'], label='RMSE Validation loss')
plt.legend();
X_train_pred = model.predict(X_train, verbose=0)
train_mae_loss = np.mean(np.abs(X_train_pred - X_train), axis=1)
plt.hist(train_mae_loss, bins=50)
plt.xlabel('Train MAE loss')
plt.ylabel('Number of Samples');
def evaluate_prediction(predictions, actual, model_name):
errors = predictions - actual
mse = np.square(errors).mean()
rmse = np.sqrt(mse)
mae = np.abs(errors).mean()
print(model_name + ':')
print('Mean Absolute Error: {:.4f}'.format(mae))
print('Root Mean Square Error: {:.4f}'.format(rmse))
print('Mean Square Error: {:.4f}'.format(mse))
print('')
return mae,rmse,mse
mae,rmse,mse = evaluate_prediction(X_train_pred, X_train,MODEL)
GRU: Mean Absolute Error: 0.1655 Root Mean Square Error: 0.5845 Mean Square Error: 0.3417
model.save(MODELFILENAME+'.h5')
#càlcul del threshold de test
def calculate_threshold(X_test, X_test_pred):
distance = np.sqrt(np.mean(np.square(X_test_pred - X_test),axis=1))
"""Sorting the scores/diffs and using a 0.80 as cutoff value to pick the threshold"""
distance.sort();
cut_off = int(0.99 * len(distance));
threshold = distance[cut_off];
return threshold
for col in columns:
print ("####################### "+col +" ###########################")
#Standardize the test data
scaler = StandardScaler()
test_cpy = test.copy()
test[col] = scaler.fit_transform(test[[col]])
#creem seqüencia amb finestra temporal per les dades de test
X_test1, y_test1 = create_sequences(test[[col]], test[col])
print(f'Testing shape: {X_test1.shape}')
#evaluem el model
eval = model.evaluate(X_test1, y_test1)
print("evaluate: ",eval)
#predim el model
X_test1_pred = model.predict(X_test1, verbose=0)
evaluate_prediction(X_test1_pred, X_test1,MODEL)
#càlcul del mae_loss
test1_mae_loss = np.mean(np.abs(X_test1_pred - X_test1), axis=1)
test1_rmse_loss = np.sqrt(np.mean(np.square(X_test1_pred - X_test1),axis=1))
# reshaping test prediction
X_test1_predReshape = X_test1_pred.reshape((X_test1_pred.shape[0] * X_test1_pred.shape[1]), X_test1_pred.shape[2])
# reshaping test data
X_test1Reshape = X_test1.reshape((X_test1.shape[0] * X_test1.shape[1]), X_test1.shape[2])
threshold_test = calculate_threshold(X_test1Reshape,X_test1_predReshape)
test1_score_df = pd.DataFrame(test[TIME_STEPS:])
test1_score_df['loss'] = test1_rmse_loss.reshape((-1))
test1_score_df['threshold'] = threshold_test
test1_score_df['anomaly'] = test1_score_df['loss'] > test1_score_df['threshold']
test1_score_df[col] = test[TIME_STEPS:][col]
#gràfic test lost i threshold
fig = go.Figure()
fig.add_trace(go.Scatter(x=test1_score_df.index, y=test1_score_df['loss'], name='Test loss'))
fig.add_trace(go.Scatter(x=test1_score_df.index, y=test1_score_df['threshold'], name='Threshold'))
fig.update_layout(showlegend=True, title='Test loss vs. Threshold')
fig.show()
#Posem les anomalies en un array
anomalies1 = test1_score_df.loc[test1_score_df['anomaly'] == True]
anomalies1.shape
print('anomalies: ',anomalies1.shape); print();
#Gràfic dels punts i de les anomalíes amb els valors de dades transformades per verificar que la normalització que s'ha fet no distorssiona les dades
fig = go.Figure()
fig.add_trace(go.Scatter(x=test1_score_df.index, y=scaler.inverse_transform(test1_score_df[col]), name=col))
fig.add_trace(go.Scatter(x=anomalies1.index, y=scaler.inverse_transform(anomalies1[col]), mode='markers', name='Anomaly'))
fig.update_layout(showlegend=True, title='Detected anomalies')
fig.show()
print ("######################################################")
####################### PM1 ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy test[col] = scaler.fit_transform(test[[col]])
Testing shape: (980, 18, 1) 31/31 [==============================] - 0s 4ms/step - loss: 0.4802 - mse: 0.6545 - rmse: 0.5493 evaluate: [0.4801890552043915, 0.6545266509056091, 0.5493398308753967] GRU: Mean Absolute Error: 0.1995 Root Mean Square Error: 0.5204 Mean Square Error: 0.2709
anomalies: (18, 10)
###################################################### ####################### PM25 ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (980, 18, 1) 31/31 [==============================] - 0s 3ms/step - loss: 0.4760 - mse: 0.6295 - rmse: 0.5400 evaluate: [0.4759978950023651, 0.6295107007026672, 0.5400090217590332] GRU: Mean Absolute Error: 0.2073 Root Mean Square Error: 0.5089 Mean Square Error: 0.2589
anomalies: (18, 10)
###################################################### ####################### PM10 ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (980, 18, 1) 31/31 [==============================] - 0s 3ms/step - loss: 0.4955 - mse: 0.6228 - rmse: 0.5575 evaluate: [0.4955466091632843, 0.6227946877479553, 0.5575345158576965] GRU: Mean Absolute Error: 0.2132 Root Mean Square Error: 0.4944 Mean Square Error: 0.2444
anomalies: (18, 10)
###################################################### ####################### PM1ATM ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (980, 18, 1) 31/31 [==============================] - 0s 3ms/step - loss: 0.4802 - mse: 0.6545 - rmse: 0.5494 evaluate: [0.4802359342575073, 0.6545409560203552, 0.5494410395622253] GRU: Mean Absolute Error: 0.1996 Root Mean Square Error: 0.5202 Mean Square Error: 0.2706
anomalies: (18, 10)
###################################################### ####################### PM25ATM ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (980, 18, 1) 31/31 [==============================] - 0s 2ms/step - loss: 0.4760 - mse: 0.6295 - rmse: 0.5400 evaluate: [0.4759978950023651, 0.6295107007026672, 0.5400090217590332] GRU: Mean Absolute Error: 0.2073 Root Mean Square Error: 0.5089 Mean Square Error: 0.2589
anomalies: (18, 10)
###################################################### ####################### PM10ATM ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (980, 18, 1) 31/31 [==============================] - 0s 4ms/step - loss: 0.4954 - mse: 0.6231 - rmse: 0.5575 evaluate: [0.4953862130641937, 0.6230977773666382, 0.5575035214424133] GRU: Mean Absolute Error: 0.2132 Root Mean Square Error: 0.4942 Mean Square Error: 0.2442
anomalies: (18, 10)
######################################################